/*
 * @Description: 存放全局函数的
 */
/*global _ctxPath*/
import emitter from '@/utils/emitter';
import globalMethods from '@/plugins/methods';
import { useBaseInfoWithOut } from '@/store/modules/base-info';
//引入tab切换
import { useSummaryTabWithOut } from '@/store/modules/summary/tab';
import {useSrcCacheStore} from "@/store/modules/src-cache";
import globalData from "@/plugins/data";

const summaryTab = useSummaryTabWithOut();
const baseInfo = useBaseInfoWithOut();


/**
 * @description: matchRequestToken
 */
window.setMatchRequestToken = (data) => {
  window.matchRequestToken = data;
};

/**
 * @description: cap4表单dom加载完成
 * @param {Object}data 加载完成传回的数据
 */
window.ContentLoadedCallback = (data) => {
  console.log('ContentLoadedCallback', data);

  emitter.publish('ContentLoaded', data);
};

/**
 * @description: 相关数据，点击更多，选了复制至当前模板触发的函数
 * @param {String}formRecordid
 * @param {String}summaryId
 */
window.copyForm = (formRecordid, summaryId) => {
  emitter.publish('copyForm', { summaryId, affair: { formRecordid } });
};

window._getZWIframe = () => {
  return window.document.getElementById('zwIframe').contentWindow || window.document.zwIframe;
};

//修改正文保存日志 流版签加载项使用
window.saveUpdateContentLog=()=>{
  if (!globalData.isSummary){
    return;
  }
  let params = {};
  params.affairId = globalData.affairId;
  params.summaryId = globalData.summaryId;
  window.callBackendMethod("colManager", "saveUpdateContentLog", params);
}

//流版签编辑正文回调
window.getCanEdit = () => {
  return baseInfo.canSign || baseInfo.canEdit;
}

//流版签这样读取协同标识
window.moduleTypeName = 'collaboration'
window.currentPage = globalData.method

//工作流提交失败全局回调
window.releaseApplicationButtons = () => {
  window?.workflowModule?.resetCpMatchResult();
}

/**
 * @description 归档回调，原方法：doPigeonholeCallback
 */
window.pigeonholeChromeCollBack = (result) => {
  // 取消按钮
  if (result !== 'cancel') {
    // 确认按钮
    var pigeonholeData = result.split(',');
    // 回填内容
    var pigeonholeId = pigeonholeData[0];
    var pigeonholeName = pigeonholeData[1];
    emitter.publish('pigeonholeAddItem', {
      confirm:true,
      value: pigeonholeId,
      name: pigeonholeName,
      selected: true
    });
  }else {
    emitter.publish('pigeonholeAddItem', {
      confirm:false
    });
  }

  // this.dialog.close();
};

window.loadAndRefreshPrediction = (config) => {
  // var container = config.container;
  var contentAPI = config.contentAPI;

  var summaryId = config.summaryId;
  var formId = config.formId;
  var templateId = config.templateId;
  var processId = config.processId;
  var currentNodeId = config.currentNodeId;

  var showType = config.showType;

  var formDataId = '';

  function __exePrediction() {
    var ajaxParam = {};
    ajaxParam.summaryId = summaryId;
    ajaxParam.formDataId = formDataId;
    ajaxParam.formId = formId;
    ajaxParam.templateId = templateId;
    ajaxParam.processId = processId;
    ajaxParam.currentNodeId = currentNodeId;

    if (showType == 'dialog') {
      var urlParams = '';
      for (var key in ajaxParam) {
        urlParams += '&' + key + '=' + ajaxParam[key];
      }

      var dialog = globalMethods.legacyDialog({
        id: 'prediction_result_dialog',
        url: _ctxPath + '/workflowPrediction.do?method=prediction' + urlParams,
        width: 500,
        height: 500,
        title: $.i18n('workflow.prediction.label.title'), //流程预测
        buttons: [
          {
            text: $.i18n('common.button.cancel.label'), // 取消
            handler: function () {
              dialog.close();
            }
          }
        ]
      });
    } else {
      // var startTime = (new Date()).getTime();
      // callBackendMethod("workflowPredictionManager","doPrediction", ajaxParam,{
      //       success : function(predictionProcessVO){
      //           _renderPredictionData(predictionProcessVO, container, startTime);
      //       }
      // });
    }
  }

  // __exePrediction()
  if (contentAPI) {
    formDataId = contentAPI.getContentDataId();
    contentAPI.preSubmit({
      checkNull: false,
      needCheckRule: false,
      needSn: false,
      success: __exePrediction
    });
  } else {
    __exePrediction();
  }
};

getA8Top().up = {
  getProject: function () {
    let { relatedProject } = baseInfo;
    return {
      projectId: (relatedProject && relatedProject.projectId) || ''
    };
  }
};

//请添加一个名字为refreshWorkflow的函数，以刷新流程图页面，看到加签/减签效果！
window.refreshWorkflow = function (param) {
  console.log('refreshWorkflow', param);
  const {splitDisplay, currentWorkitemId, currentNodeId} = param;
  //更新推送人员 加签之后的
  if (typeof param !== 'boolean'){
    baseInfo.updatePushPeopleList();
  }
  //如果是加签立即收到需要设置为分离模式
  if (splitDisplay) {
    useSrcCacheStore().setParam({
      SD:splitDisplay,
      CWID:currentWorkitemId,
      currentNodeId
    })
    //设置新的url地址
    useSrcCacheStore().createShowWorkFlowUrl();
  }
  //加入成功，切换并，刷新iframe
  summaryTab.changeActiveIndex();
  let workflowWindow = summaryTab.flowIframe?.contentWindow;
  if (workflowWindow) {
    workflowWindow.location.reload();
  }
};

window._editWorkflowFn = () => {
  const {
    summary: { processId,caseId,formRecordid,templeteId,bodyType },
    nodePolicy: { flowPermAccountId},
  } = baseInfo.businessData;
  window.callBackendMethod("colManager", "getColDefaultNode", flowPermAccountId, {
    success: function success(defaultNodeMap) {
      var options = {
        targetWin: window.getCtpTop(),
        caseId: caseId,
        processId: processId,
        appName: "collaboration",
        isTemplate: !!templeteId,
        masterId: formRecordid,
        flowPermAccountId: flowPermAccountId,
        defaultPolicyId: defaultNodeMap.defaultNodeName,
        defaultPolicyName: defaultNodeMap.defaultNodeLable,
        title: $.i18n('supervise.col.label'),
        scene: 4,
        buttons: [{
          "id": "saveDBOK",
          "callBackFn": window.refreshWorkflow
        }, {
          "id": "cancel"
        }],
        SPK: "freeFlow",
        NPS: "default"
      };
      if (bodyType == "20") {
        options.SPK = "collaboration_template_form";
        options.NPS = "form";
      }
      window.showDiagram(options);
    }
  });
}


window._executePrediction = function (dialogMode) {
  const {summary, template, affair} = baseInfo.businessData;
  loadAndRefreshPrediction({
    container: "",
    contentAPI: "",
    summaryId: summary.id,
    formId: template.formAppId,
    templateId: template.id,
    processId: summary.processId,
    currentNodeId: affair?.activityId || '',
    showType: dialogMode === true ? "dialog" : ''
  })
};

window.ckEditorCoverDiv = null;

/*恶心的遮罩开始*/
window.showDialogCover = function () {
  let parentElement = document.getElementById('zw-wrapper')?.parentNode;
  if (!parentElement) {
    return;
  }
  if (!window.ckEditorCoverDiv && !globalData.isCap4) {
    window.ckEditorCoverDiv = document.createElement('div');
    let coverDiv = window.ckEditorCoverDiv;
    coverDiv.classList.add('ckEditor-cover-style')
    coverDiv.style.position = 'absolute';
    coverDiv.style.height = '100%';
    coverDiv.style.top= '0';//chrome 49 兼容性问题
    coverDiv.style.left= '0';//chrome 49 兼容性问题
    coverDiv.style.width = '100%';
    coverDiv.style.backgroundColor = 'rgb(0, 0, 0)'
    coverDiv.style.opacity = '0.5';
    parentElement.parentNode.insertBefore(coverDiv, parentElement);
  } else {
    window.ckEditorCoverDiv && (window.ckEditorCoverDiv.style.display = 'block')
  }
  emitter.publish('ckEditor-onCover', true);

}

window.removeDialogCover = function () {
  window.ckEditorCoverDiv && (window.ckEditorCoverDiv.style.display = 'none')
  emitter.publish('ckEditor-onCover', false);
}
/*恶心的遮罩结束*/

/**cap4计算触发全部透明遮罩*/
window.cap4TransparentMaskDiv = null;

/**
 * 显示遮罩
 * */
export function showCap4TransparentMask(){
  if (!window.cap4TransparentMaskDiv){
    window.cap4TransparentMaskDiv = document.createElement('div');
    let coverDiv = window.cap4TransparentMaskDiv;
    coverDiv.classList.add('transparent_mast')
    coverDiv.style.position = 'absolute';
    coverDiv.style.height = '100%';
    coverDiv.style.top= '0';
    coverDiv.style.left= '0';
    coverDiv.style.width = '100%';
    coverDiv.style.zIndex='9999'
    document.body.appendChild(coverDiv);
  }else {
    window.cap4TransparentMaskDiv.style.display = 'block';
  }
}

/**
 * 隐藏遮罩
 * */
export function hiddenCap4TransparentMask() {
  if (window.cap4TransparentMaskDiv) {
    window.cap4TransparentMaskDiv.style.display = 'none';
  }
}

//在layer弹窗点击关闭外层再套一层
// if (window.layer) {
//     const layerClose = window.layer.close;
//     window.layer.close = function (...params) {
//         console.log(...params);

//         //抛出个关闭事件
//         emitter.publish('layerClose');
//         //调用原逻辑
//         layerClose(...params);
//     };
// }
export default emitter;
